const path = require("path");
import axios from "axios";
import qs from "qs";
import Vue from "@/main";

import store from "@/store";
import { getToken, getUserInfo } from "@/utils/auth";
// eslint-disable-next-line no-unused-vars
import { MessageBox, Message } from "element-ui";
// 引入进度条
import nprogress from "nprogress";
// 因为进度条样式咱们没有引入
import "nprogress/nprogress.css";
let BASE_API = "";
const axios2 = axios.create();
axios.defaults.timeout = 10000; // 响应时间
axios2.defaults.timeout = 10000;
axios.defaults.headers.post["Content-Type"] =
  "application/x-www-form-urlencoded"; // 配置请求头
axios.defaults.baseURL = BASE_API; // 配置接口地址根目录 path.join(__dirname, process.env.VUE_APP_API)
// axios2.defaults.baseURL = path.join(__dirname, process.env.VUE_APP_API);
// //POST传参序列化(添加请求拦截器)
axios.interceptors.request.use(
  (config) => {
    // 在发送请求之前做某件事 //请求之前加入token
    let token = store.getters.token;
    if (!token) {
      token = getToken();
    }
    config.headers = {
      "Content-Type": "application/x-www-form-urlencoded",
      authorization: token, // 写自己后端传回来的token的命名，本项目为 authorization，
      ...config.headers,
    };
    if (config.method === "post") {
      if (
        config.headers["Content-Type"] === "application/x-www-form-urlencoded"
      ) {
        if (!config.data.username) {
          config.data.username =
            store.getters.username || getUserInfo().username;
        }
        config.data.rolescode =
            store.getters.rolescode || getUserInfo().rolescode;
        // 获取接口编号
        const serviceCode = config.data.serviceCode;
        // 删除接口编号
        delete config.data.serviceCode;
        // 添加token
        config.data.token = token; // 3f3623fb01bdadc665a653fa4b1279e1
        // 添加参数
        const data = {
          serviceCode,
          authorizationCode: process.env.VUE_APP_SQM,
          tStamp: Date.now(),
          data: JSON.stringify({ data: config.data }),
        };
        config.data = qs.stringify(data); // 序列化post 参数
      }
    }
    nprogress.start();
    if (config.url.indexOf("1api") !== -1) {
      BASE_API = "";
    } else {
      BASE_API = path.join(__dirname, process.env.VUE_APP_API);
    }
    config.url = BASE_API + config.url;
    return config;
  },
  (error) => {
    console.log(error, "发送请求时");
    Message({
      message: "请求超时！",
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);
// 返回状态判断(添加响应拦截器)
axios.interceptors.response.use(
  // 对响应数据做些事
  (response) => {
    nprogress.done();
    const res = response.data;
    // 服务器响应失败干什么
    if (res.code !== "0" && res.status !== "success" && !res.attachid) {
      Message({
        message: res.msg || "Error",
        type: "error",
        duration: 5 * 1000,
      });
      if (res.code === "100" && Vue.$route.name !== "login") {
        const hasGetUserInfo = store.getters.name;
        if (hasGetUserInfo) {
          MessageBox.confirm(
            "您已注销，您可以取消以停留在此页面，或重新登录",
            "确认注销",
            {
              confirmButtonText: "确认",
              cancelButtonText: "取消",
              type: "warning",
            }
          ).then(() => {
            store.dispatch("user/resetToken").then(() => {
              location.reload();
            });
          });
        }
      }
      return Promise.reject(res);
    } else {
      // 响应成功
      if (res.msg) {
        Message({
          message: res.msg,
          type: "success",
          duration: 5 * 1000,
        });
      }
      nprogress.done();
      return res.data || res;
    }
  },
  (err) => {
    nprogress.done();
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          err.message = "请求错误(400)";
          break;
        case 401:
          err.message = "未授权，请重新登录(401)";
          break;
        case 403:
          err.message = "拒绝访问(403)";
          break;
        case 404:
          err.message = "请求出错(404)";
          break;
        case 408:
          err.message = "请求超时(408)";
          break;
        case 500:
          err.message = "服务器错误(500)";
          break;
        case 501:
          err.message = "服务未实现(501)";
          break;
        case 502:
          err.message = "网络错误(502)";
          break;
        case 503:
          err.message = "服务不可用(503)";
          break;
        case 504:
          err.message = "网络超时(504)";
          break;
        case 505:
          err.message = "HTTP版本不受支持(505)";
          break;
        default:
          err.message = `连接出错(${err.response.status})!`;
      }
    }
    // if (err?.code === 'ECONNABORTED') {
    //   err.message = '连接服务器失败!'
    // }
    // else {
    //   err.message = '连接服务器失败!'
    // }
    Message({
      message: err.message,
      type: "error",
      duration: 5 * 1000,
    });
    console.log(err, "响应接口");
    return Promise.reject(err); // 接口500抛出异常（不走页面逻辑）
  }
);

axios2.interceptors.request.use(
  (config) => {
    //     //在发送请求之前做某件事 //请求之前加入token
    if (store.getters.token) {
      config.headers = {
        authorization: getToken(), // 写自己后端传回来的token的命名，本项目为 authorization，
        "Content-Type": "application/json;charset=UTF-8",
      };
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

axios2.interceptors.response.use(
  // 对响应数据做些事
  (response) => {
    const res = response.data;
    // 服务器响应失败干什么
    if (res.code !== 20000 && res.code !== "0" && res.status !== "success") {
      Message({
        message: res.message || "Error",
        type: "error",
        duration: 5 * 1000,
      });
      return Promise.reject(new Error(res.message || "Error"));
    } else {
      // 响应成功
      return res;
    }
  },
  (error) => {
    console.log("err" + error); // for debug
    Message({
      message: error.message,
      type: "error",
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);
// 返回一个Promise(发送请求头为application/json的post请求)
function jsonpost(params, config) {
  const { url } = params; // JSON.parse(JSON.stringify(params))
  const { data } = params;
  return new Promise((resolve, reject) => {
    axios2
      .post(url, data, config)
      .then(
        (response) => {
          resolve(response);
        },
        (err) => {
          reject(err);
        }
      )
      .catch((error) => {
        reject(error);
      });
  });
}

function jsonget(url, params) {
  return new Promise((resolve, reject) => {
    axios2
      .get(url, params)
      .then(
        (response) => {
          resolve(response);
        },
        (err) => {
          reject(err);
        }
      )
      .catch((error) => {
        reject(error);
      });
  });
}

function jsondelete(url, params) {
  return new Promise((resolve, reject) => {
    axios2
      .delete(url, { data: params })
      .then(
        (response) => {
          resolve(response);
        },
        (err) => {
          reject(err);
        }
      )
      .catch((error) => {
        reject(error);
      });
  });
}

// 返回一个Promise(发送post请求)
function post(params, config) {
  let { url } = params; // JSON.parse(JSON.stringify(params))
  const { data, serviceCode } = params;
  if (serviceCode) {
    data["serviceCode"] = serviceCode;
  }
  if (!url) {
    url = "/WebApi";
  }
  return new Promise((resolve, reject) => {
    axios
      .post(url, data, config)
      .then(
        (response) => {
          resolve(response);
        },
        (err) => {
          reject(err);
        }
      )
      .catch((error) => {
        reject(error);
      });
  });
}
// 返回一个Promise(发送get请求)
function get(params, config) {
  const { url } = params; // JSON.parse(JSON.stringify(params))
  const { data } = params;
  return new Promise((resolve, reject) => {
    axios
      .get(url, { params: data }, config)
      .then(
        (response) => {
          resolve(response);
        },
        (err) => {
          reject(err);
        }
      )
      .catch((error) => {
        reject(error);
      });
  });
}
function deletefn(url, params) {
  return new Promise((resolve, reject) => {
    axios
      .delete(url + [params])
      .then(
        (response) => {
          resolve(response);
        },
        (err) => {
          reject(err);
        }
      )
      .catch((err) => {
        reject(err);
      });
  });
}

function download(url, params) {
  return new Promise((resolve, reject) => {
    axios2
      .post(url, params, { responseType: "blob" })
      .then(
        (response) => {
          resolve(response);
        },
        (err) => {
          reject(err);
        }
      )
      .catch((error) => {
        reject(error);
      });
  });
}

export default {
  get,
  post,
  deletefn,
  jsonpost,
  jsonget,
  jsondelete,
  download,
};
